package mongo

import (
	"github.com/cdongyang/library/utils"
	mgo "gopkg.in/mgo.v2"
)

var conf struct {
	Socket string
	DB     string
}

var Users, Class, Notice Mongo

func init() {
	utils.PanicError(utils.LoadCurrentDirJSONFile("config.json", &conf))
	session, err := mgo.Dial(conf.Socket + "/" + conf.DB)
	utils.PanicError(err)

	Users.session = session
	Users.collection = "users"
	Class.session = session
	Class.collection = "class"
	Notice.session = session
	Notice.collection = "notice"
}

type Mongo struct {
	session    *mgo.Session
	collection string
	c          *mgo.Collection
}

func (m *Mongo) WithC(job func(c *mgo.Collection) error) error {
	s := m.session.New()
	defer s.Close()
	return job(s.DB(conf.DB).C(m.collection))
}
